# 实现对ToorBar条目后端的编写操作
from django.core.cache import cache
from django.forms import model_to_dict
from django.views.decorators.http import require_POST
import json
from casedemo9_smscode.models import CaseDemo9User
from casedemo9_smscode.utils import decode_jwt
from django.http import JsonResponse
from django.views.decorators.http import require_GET
from django.views.decorators.csrf import csrf_exempt

SECRET_KEY = "djangobase+vue"
def check_info_exists(model_class, field_name, value):
    """
    检查某个 model_class 是否存在指定字段等于 value 的记录
    :param model_class: Django 模型类，例如 User、Article
    :param field_name: 要查询的字段名（字符串）
    :param value: 要匹配的值
    :return: True/False
    """
    filter_kwargs = {field_name: value}
    return model_class.objects.filter(**filter_kwargs).exists()  # 返回存在/不存在

@csrf_exempt
@require_POST
def updateUserInfo(request):# 更新用户信息
    try:
        print("当前的模块是updateUserInfo")
        token = request.headers.get('Authorization')
        data = json.loads(request.body)# 获取需要知道的data信息
        realname=data.get('realname',None)
        phone=data.get('phone',None)
        sex=data.get('sex',None)
        email=data.get('email',None)
        card=data.get('card',None)
        address=data.get('address',None)
        descrption=data.get('descrption',None)
        username=data.get('username',None)
        print(realname,phone,sex,email,card,address,descrption,username)
        # 根据username查询用户信息
        userinfo=CaseDemo9User.objects.filter(username=username).first()
        if not userinfo:
            return JsonResponse({'code': 400, 'msg': '用户不存在'}, status=400)
        else:
            if userinfo.email!=email:
                if check_info_exists(CaseDemo9User, 'email', email):
                    return JsonResponse({'code': 400, 'msg': '该邮箱已存在'}, status=400)
                else:
                    CaseDemo9User.objects.filter(username=username).update(email=email)
            if userinfo.phone!=phone:
                if check_info_exists(CaseDemo9User, 'phone', phone):
                    return JsonResponse({'code': 400, 'msg': '该手机号已存在'}, status=400)
                else:
                    CaseDemo9User.objects.filter(username=username).update(phone=phone)
            if userinfo.card!=card:
                if check_info_exists(CaseDemo9User, 'card', card):
                    return JsonResponse({'code': 400, 'msg': '该身份证号已存在'}, status=400)
                else:
                    CaseDemo9User.objects.filter(username=username).update(card=card)
            if userinfo.realname!=realname:
                CaseDemo9User.objects.filter(username=username).update(realname=realname)
            if userinfo.sex!=sex:
                CaseDemo9User.objects.filter(username=username).update(sex=sex)
            if userinfo.address!=address:
                CaseDemo9User.objects.filter(username=username).update(address=address)
            if userinfo.descrption!=descrption:
                CaseDemo9User.objects.filter(username=username).update(descrption=descrption)
            return JsonResponse({'code': 888, 'msg': '用户信息更新成功'}, status=200)
    except Exception as e:
        print("出问题了")
        return JsonResponse({'code': 500, 'msg': f'服务异常: {str(e)}'}, status=500)
@csrf_exempt
@require_POST
def getUserInfo(request):# 获取用户信息
    try:
        print("当前的模块是getUserInfo")
        token = request.headers.get('token')
        print(f"当前的token:{token}")
        # 解析token获得username
        username = decode_jwt(token=token)
        userinfo = CaseDemo9User.objects.filter(username=username).first()
        if not userinfo:
            return JsonResponse({'code': 400, 'msg': '用户不存在'}, status=400)
        else:
            return JsonResponse({'code': 888, 'msg': '用户信息获取成功','data':model_to_dict(userinfo)}, status=200)
    except Exception as e:
        return JsonResponse({'code': 500, 'msg': f'服务异常: {str(e)}'}, status=500)


@csrf_exempt  # 如果前端没有设置 CSRF token，可临时关闭（更安全的是配置 CSRF token）
@require_GET
def logout_view(request):
    token = request.headers.get('token')
    print(f"logout_view:当前的token:{token}")
    # 解析token获得username
    username = decode_jwt(token=token)
    userinfo = CaseDemo9User.objects.filter(username=username).first()
    if not userinfo:
        return JsonResponse({'code': 400, 'msg': '用户不存在'}, status=400)
    else:
        # 删除token缓存
        cache.delete(f'casedemo9_user_info_{userinfo.useronlyID}')
        cache.delete(f'token')
        return JsonResponse({'code': 888, 'msg': '用户信息获取成功','data':model_to_dict(userinfo)}, status=200)
@csrf_exempt
@require_POST
def chagnePwd(request):
    try:
        print("当前的模块是chagnePwd")
        data = json.loads(request.body)  # 获取需要知道的data信息
        oldpassword = data.get('oldpassword', None)
        newpassword = data.get('password',None)
        token = request.headers.get('token')
        print(f"logout_view:当前的token:{token}")
        # 解析token获得username
        username = decode_jwt(token=token)
        userinfo = CaseDemo9User.objects.filter(username=username).first()
        if not userinfo:
            return JsonResponse({'code': 400, 'msg': '用户不存在'}, status=400)
        else:
            if userinfo.password!=oldpassword:
                return JsonResponse({'code': 400, 'msg': '旧密码错误'}, status=400)
            else:
                CaseDemo9User.objects.filter(username=username).update(password=newpassword)
                return JsonResponse({'code': 888, 'msg': '密码修改成功'}, status=200)
    except Exception as e:
        return JsonResponse({'code': 500, 'msg': f'服务异常: {str(e)}'}, status=500)
